#!/bin/bash

# ArXiv Subscription Platform - Quick Deploy Script
# One-command deployment for development or production

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_status() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Configuration
ENVIRONMENT=${1:-development}
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

print_status "ArXiv Subscription Platform - Quick Deploy"
print_status "Environment: $ENVIRONMENT"

# Install system dependencies
install_dependencies() {
    print_status "Installing system dependencies..."
    
    if command -v apt-get &> /dev/null; then
        # Ubuntu/Debian
        sudo apt-get update
        sudo apt-get install -y python3 python3-venv python3-pip postgresql postgresql-contrib redis-server nginx nodejs npm bc
    elif command -v yum &> /dev/null; then
        # RHEL/CentOS
        sudo yum install -y python3 python3-pip postgresql postgresql-server redis nginx nodejs npm bc
        sudo postgresql-setup initdb || true
    elif command -v brew &> /dev/null; then
        # macOS
        brew install python3 postgresql redis nginx node
    else
        print_warning "Unknown package manager. Please install manually:"
        print_warning "- Python 3.8+"
        print_warning "- PostgreSQL"
        print_warning "- Redis"
        print_warning "- Node.js (optional)"
        print_warning "- nginx (optional)"
    fi
}

# Setup PostgreSQL
setup_postgresql() {
    print_status "Setting up PostgreSQL..."
    
    # Start PostgreSQL service
    if command -v systemctl &> /dev/null; then
        sudo systemctl start postgresql 2>/dev/null || print_warning "PostgreSQL may already be running"
        sudo systemctl enable postgresql 2>/dev/null || true
        sleep 2  # Give PostgreSQL time to start
    elif command -v brew &> /dev/null; then
        brew services start postgresql 2>/dev/null || print_warning "PostgreSQL may already be running"
        sleep 2
    else
        print_warning "Unable to start PostgreSQL automatically. Please start it manually."
    fi
    
    # Wait for PostgreSQL to be ready
    for i in {1..10}; do
        if sudo -u postgres psql -c '\q' 2>/dev/null; then
            break
        fi
        print_status "Waiting for PostgreSQL to be ready... ($i/10)"
        sleep 2
    done
    
    # Create database and user
    sudo -u postgres psql << EOF || true
DO \$\$
BEGIN
    IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'arxiv_user') THEN
        CREATE USER arxiv_user WITH PASSWORD 'arxiv_pass';
    END IF;
END
\$\$;
CREATE DATABASE arxiv_platform OWNER arxiv_user;
GRANT ALL PRIVILEGES ON DATABASE arxiv_platform TO arxiv_user;
EOF
    
    print_success "PostgreSQL setup completed"
}

# Setup Redis
setup_redis() {
    print_status "Setting up Redis..."
    
    # Start Redis service
    if command -v systemctl &> /dev/null; then
        sudo systemctl start redis
        sudo systemctl enable redis
    elif command -v brew &> /dev/null; then
        brew services start redis
    else
        redis-server --daemonize yes
    fi
    
    print_success "Redis setup completed"
}

# Main deployment
deploy() {
    case $ENVIRONMENT in
        "development"|"dev")
            print_status "Development deployment"
            ;;
        "production"|"prod")
            print_status "Production deployment"
            install_dependencies
            setup_postgresql
            setup_redis
            ;;
        "quick")
            print_status "Quick deployment (existing dependencies)"
            ;;
        *)
            print_error "Unknown environment: $ENVIRONMENT"
            print_status "Usage: $0 [development|production|quick]"
            exit 1
            ;;
    esac
    
    # Run build script
    print_status "Building platform..."
    "$PROJECT_ROOT/build.sh"
    
    # Start services
    print_status "Starting services..."
    cd "$PROJECT_ROOT/build"
    ./start.sh
    
    print_success "Deployment completed!"
    print_status "Platform is running at:"
    print_status "  API: http://localhost:8000"
    print_status "  Docs: http://localhost:8000/docs"
    print_status "  Health: http://localhost:8000/health"
    
    # Wait a moment and check health
    sleep 5
    if curl -s http://localhost:8000/health > /dev/null; then
        print_success "Platform is healthy and ready!"
    else
        print_warning "Platform may still be starting up. Check logs in build/logs/"
    fi
}

# Cleanup function
cleanup() {
    print_status "Cleaning up previous deployment..."
    
    # Stop existing services
    if [ -f "$PROJECT_ROOT/build/stop.sh" ]; then
        cd "$PROJECT_ROOT/build"
        ./stop.sh || true
    fi
    
    # Clean build directory
    "$PROJECT_ROOT/build.sh" clean
}

# Handle commands
case "${2:-}" in
    "clean")
        cleanup
        ;;
    "restart")
        cleanup
        deploy
        ;;
    *)
        deploy
        ;;
esac